package com.sfy.wx.controller;


import com.sfy.wx.handler.WxChatMsgFactory;
import com.sfy.wx.handler.WxChatMsgHandler;
import com.sfy.wx.util.MessageUtil;
import com.sfy.wx.util.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class CallBackController {

    private static final String token = "123456";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    /**
     * 回调消息校验(验签)
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknow";
    }

    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接受到微信的请求：requestBody:{}", requestBody);
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        String msgType = msgMap.get("MsgType");
        String event = msgMap.get("Event") == null ? "" : msgMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            stringBuilder.append(".");
            stringBuilder.append(event);
        }
        String msgTypeKey = stringBuilder.toString();
        WxChatMsgHandler handler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(handler)) {
            return "unknow";
        }
        String replyContent = handler.dealMsg(msgMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }
}
